<?php

namespace app\api\controller;
use app\api\service\Payment as PaymentService;
use app\common\enum\OrderType as OrderTypeEnum;
use think\Db;
use think\Log;
use app\api\service\shanghui\PaySuccess;
use app\api\model\User as UserModel;
use app\api\model\user\BalanceLog as BalanceLogModel;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
/**
 * 商会相关的操作
 * Class Coupon
 * @package app\api\controller
 */
class Shanghui extends Controller
{
    // 切换商会
    public function uphui($shanghui_id){
        $user = $this->getUser();
        $info = Db::name("shanghui_user")
            ->where("shanghui_id",$shanghui_id)
            ->where("user_id",$user['user_id'])->find();
        Db::name("user")->where("user_id",$user['user_id'])->update(['shanghui_id'=>$shanghui_id,'grade_id'=>$info['grade_id']]);
        return $this->renderSuccess([],"商会已经切换");
    }
    /**
     * 购买商会人数升级-生成订单
     */
    public function buy(){
        $paymothed = 10;//10余额支付，20微信支付
        // 用户信息
        $user = $this->getUser();
        $param = input('param.');
        //限制数量
        if($param['limit'] >0){
            $total = Db::name('shanghui_order')->where('shanghui_id',$user['shanghui_id'])->where('pay_status',20)->where("plan_id",$param['id'])->count();
            // 超量提示
            if($total >= $param['limit']){
                return $this->renderError("您已经购买过了！");
            }
        }
        $payStatus = 10; //支付状态
        $pay_time  = 0;  //支付时间
         // 余额支付
        if($paymothed == '10')
        {
            $userInfo= UserModel::detail($user['user_id']);
            if($userInfo['balance']<$param['price']){
                return $this->renderError("余额不足！");
            }
            $payStatus = 20; //支付状态
            $pay_time  =time();
        }
        
        $order_no = $this->createOrderNo();
        $idata = [
            'user_id'=>$user['user_id'],
            'order_no'=>$order_no,
            'peoplenumber'=>$param['people'],
            'plan_id'=>$param['id'],
            'pay_price'=>$param['price'],
            'shanghui_id'=>$user['shanghui_id'],
            'wxapp_id'=>$param['wxapp_id'],
            'create_time'=>time(),
            'update_time'=>time(),
            'pay_status'=>$payStatus,
            'pay_time'=>$pay_time
        ];
        Db::name('shanghui_order')->insert($idata);
        // 微信支付
        if($paymothed == '20'){
            $model = Db::name('shanghui_order')->where('order_no',$order_no)->find();
            // 构建微信支付
            $payment = PaymentService::wechat(
                $user,
                $model['order_id'],
                $model['order_no'],
                $model['pay_price'],
                OrderTypeEnum::SHANGHUI
            );
        }else{
            // 更新用户余额
            $userInfo->setDec('balance', $param['price']);
            // 商会升级(消费日志)
            BalanceLogModel::add(SceneEnum::CONSUME, [
                'user_id'  => $userInfo['user_id'],
                'money'    => -$param['price'],
            ], ['order_no' => $order_no]);
            $data['transaction_id'] = time();
            // 更新商会相关状态
            $model = new PaySuccess($order_no,$payStatus);
            $model->onPaySuccess(10);
        }
        // 状态提醒
        $message = ['success' => '升级成功', 'error' => '订单未支付'];
        return $this->renderSuccess(compact('payment', 'message'), $message);
    }
    /**
     * 生成订单号
     * @return string
     */
    private function createOrderNo($prefix = 'SH')
    {
        return 'SH'.date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}